/**
 * 
 */
package com.yyq.sos.util.filedownload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.sql.Blob;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

public class FileDownloadHandle {

	public static void downloadFile(Blob blob, String name, HttpServletResponse response) {
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			inputStream = blob.getBinaryStream();
			outputStream = response.getOutputStream();
			response.setContentType("application/octet-stream; charset=UTF-8");
			response.setHeader("Content-Disposition", "attachment; filename=\""
					+ URLEncoder.encode(name, "UTF-8") + "\"");
			IOUtils.copy(inputStream,outputStream);
			outputStream.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(inputStream);
			IOUtils.closeQuietly(outputStream);
		}
		
	}

	public static void downloadFile(byte[] content, String name, HttpServletResponse response) {
//		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
//			inputStream = input;
			outputStream = response.getOutputStream();
			response.setContentType("application/octet-stream; charset=UTF-8");
			response.setHeader("Content-Disposition", "attachment; filename=\""
					+ URLEncoder.encode(name, "UTF-8") + "\"");
			IOUtils.write(content, outputStream);
			outputStream.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
//			IOUtils.closeQuietly(inputStream);
			IOUtils.closeQuietly(outputStream);
		}
	}

	public static void downloadFile(String filePath,String showName,String attachmentName, HttpServletResponse response){
		File file = new File(filePath+File.separator+attachmentName);
		if(!file.exists()){
			return;
		}
		OutputStream os = null;
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			os = response.getOutputStream();
			response.setContentType("application/octet-stream; charset=UTF-8");
			response.setHeader("Content-Disposition", "attachment; filename=\""
					+ URLEncoder.encode(showName, "UTF-8") + "\"");
			
			byte[] b = new byte[2048];
			int len = -1;
			while ((len = fis.read(b, 0, b.length)) != -1) {
				os.write(b, 0, len);
				os.flush();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				if(fis != null){
					fis.close();
				}
				if(os != null){
					os.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
